/**
 * @Auther: zhatiai
 * @Date:2024/2/22 10:04
 */

package api

import (
	kerror "kyland.com/eagle/lib/error"
	"kyland.com/eagle/manager"
)

func GetTask(ctx *Context) {
	aiTask := &manager.AITask{}
	ctx.param(aiTask, []R{"name"})

	t, err := manager.GetTask(manager.TaskPrefix, aiTask)
	if err != nil {
		ctx.jsonFailure(kerror.ErrGetTaskFailed.AddErr(err).Error())
	}

	ctx.jsonSuccess(t)
}

func GetTaskTime(ctx *Context) {
	aiTask := &manager.AITask{}
	ctx.param(aiTask, []R{"src"})

	t, err := manager.GetTask(manager.UnFinishedPrefix, aiTask)
	if err != nil {
		ctx.jsonFailure(kerror.ErrGetTaskFailed.AddErr(err).Error())
	}

	ctx.jsonSuccess(t)
}

func ExecuteTask(ctx *Context) {
	aiTask := &manager.AITask{}
	ctx.param(aiTask, []R{"name"})
	//begin := time.Now()
	//_, filename := filepath.Split(aiTask.Name)
	//taskChange := fmt.Sprintf("%s-status", filename)
	res := manager.CreateTasks(aiTask)
	if res == nil {
		ctx.jsonFailure("task is alreay exist, please choose another name")
	}
	ctx.jsonSuccess(res)
}

func RequestTask(ctx *Context) {
	aiTask := &manager.AITask{}
	ctx.param(aiTask, []R{"name", "master"})

	manager.Request(aiTask)
	ctx.jsonSuccess([]*manager.AITask{aiTask})
}

func TaskStatus(ctx *Context) {
	aiTask := manager.AITask{}
	ctx.param(&aiTask, []R{"name", "src"})

	status := manager.GetTaskStatus(aiTask)
	ctx.jsonSuccess(status)
}

func TaskNotify(ctx *Context) {
	aiTask := manager.AITask{}
	ctx.param(&aiTask, []R{"src"})

	status := manager.Notify(aiTask)
	ctx.jsonSuccess(status)
}

func GetTasks(ctx *Context) {

	t, err := manager.GetTasks(manager.TaskPrefix)
	if err != nil {
		ctx.jsonFailure(kerror.ErrGetTaskFailed.AddErr(err).Error())
	}

	ctx.jsonSuccess(t)
}

func DeleteTask(ctx *Context) {
	aiTask := &manager.AITask{}
	ctx.param(aiTask, []R{"name"})

	t, err := manager.DeleteTask(manager.TaskPrefix, aiTask)
	if err != nil {
		ctx.jsonFailure(kerror.ErrGetTaskFailed.AddErr(err).Error())
	}

	ctx.jsonSuccess(t)
}
